import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import { Notification } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
      // config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImRlMTdhYzZlLWUzOWEtNDI1OS1iNGNjLWYwNDc5MmM4MTFkZiJ9.YsnIoHhbnWU330jOWnfmOr56hFYIM2EnVtpwe6c0esR2_B0BncTuF0EY3TMQKFVYLw-7EwQPlSDAOoIn584Ldw'
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 5000
        })
        return Promise.reject(error)
      }
    }
    if (code) {
      // if (code === 401) {
      //   store.dispatch('user/logout').then(() => {
      //     // 用户登录界面提示
      //     Cookies.set('point', 401)
      //     location.reload()
      //   })
      // } else {
      //   const errorMsg = error.response.data.message
      //   if (errorMsg !== undefined) {
      //     Notification.error({
      //       title: errorMsg,
      //       duration: 5000
      //     })
      //   }
      // }
    } else {
      Notification.error({
        title: '接口请求失败',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }
)

export default service
